layui.config({
    base: "js/"
}).use(['form', 'layer', 'jquery', 'laypage','laytpl','util'], function () {
    var form = layui.form
        , layer = parent.layer === undefined ? layui.layer : parent.layer
        , laypage = layui.laypage,laytpl = layui.laytpl, $ = layui.jquery;

    dataList(1);

    /**
     * 查询
     */
    form.on('submit(queryForm)', function(data){
        dataList(1);
        return false;
    });

    /**
     * 查询数据列表
     * @param number
     */
    function dataList(number) {
        var options = {
            dataType: "json",
            success: function (data) {
                console.log(data)
                if(data && data.error) {
                    layer.msg(data.error.msg);
                    return;
                }
                var listData = {"list":data.page.records,"userStatusMap":data.userStatusMap};
                var getTpl = dataListTpl.innerHTML,view = document.getElementById('listDataBody');

                laytpl(getTpl).render(listData, function(html){
                    view.innerHTML = html;
                });
                form.render();
                if(number === 1) {
                    //分页标签
                    pageBar(data.page.total,data.page.size);
                }
            },
            error: function (e) {
                layer.msg(JSON.stringify(e));
            }
        };
        $("#listForm").ajaxSubmit(options);
    }

    /**
     * 数据分页
     * @param count
     * @param limit
     */
    function pageBar(count,limit) {
        laypage.render({
            elem: "page",
            limit: limit,
            count: count,
            theme: '#1E9FFF',
            layout: ['count', 'prev', 'page', 'next'],
            jump: function(obj, first){
                if(!first){
                    $("#number").val(obj.curr);
                    dataList(obj.curr);
                }
            }
        });
    }

    /**
     * 添加用户
     */
    $("body").on("click", ".usersAdd_btn", function () {
        addOrEdit("添加用户", "/user/add", "添加", false);
    })

    /**
     * 编辑用户
     */
    $("body").on("click", ".userEdit", function () {
        var id = $(this).data("id");
        addOrEdit("编辑用户", "/m/user/update/" + id, "编辑", true, "/m/user/" + id);
    })

    /**
     * 添加或编辑用户
     * @param title
     * @param postUrl
     * @param yesBtnName
     * @param isEdit
     * @param queryUrl
     */
    function addOrEdit(title, postUrl, yesBtnName, isEdit, queryUrl) {
        var index = layui.layer.open({
            title: title,
            anim: 2,
            content: $("#addUser").html(),
            btn: [yesBtnName, '取消'],
            yes: function () {
                var username = $(".username").val(), password = $(".password").val() ,email =$(".email").val() ;
                post(postUrl, {
                    "username": username,
                    "password": password,
                    "email": email
                }, function (data) {
                    if (data.code == 0) {
                        layui.layer.close(index);
                        layer.msg(data.msg || "操作成功~", {icon: 6});
                        dataList(1);
                    }else{
                        layer.msg(data.msg?data.msg:"添加失败~~~", {icon: 5});
                    }
                })

            },
            success: function () {
                if (isEdit) {
                    get(queryUrl, null, function (data) {
                        if (data.code == 0) {
                            $(".username").val(data.user.username);
                            $(".password").val(data.user.password);
                        }

                    })
                }
            }
        })
    }

    /**
     * 冻结用户
     */
    form.on('switch(isShow)', function (obj) {
        var id = obj.elem.getAttribute("data-id");
        var status = 0;
        if (obj.elem.checked) {
            status = -1;
        }
        obj.elem.disabled = true;
        post("/user/update/status/" + id, {
            "status": status
        }, function (data) {
            if (data.code == 0) {
                obj.elem.disabled = false;
                layer.msg(data.msg, {icon: 6, time: 500});
                if (status == -1) {
                    obj.othis.parent().prev().text("冻结").css({"color": "#35A7FE"})
                } else {
                    obj.othis.parent().prev().text("正常").css({"color": "#666"});
                }

            }
        });
    })

    /**
     * 假删除用户（系统注销），恢复正常
     */
    $("body").on("click", ".userDel", function () {
        var _this = $(this);
        layer.confirm('确定进行此操作？', {
            icon: 3,
            title: '提示信息'
        }, function (index) {

            var id = _this.attr("data-id"),status = _this.attr("status");
            post("/user/update/status/" + id, {"status":status}, function (data) {
                layer.msg(data.msg || "操作成功~", {icon: 6});
                layer.close(index);
                dataList(1);
            }, false, false);

        });
    })

    /**
     * 批量冻结
     */
	$(".batchDel").click(function(){
		var $checkbox = $('.users_list tbody input[type="checkbox"][name="checked"]');
		var $checked = $('.users_list tbody input[type="checkbox"][name="checked"]:checked');
		if($checkbox.is(":checked")){
			layer.confirm('确定批量冻结选中的用户？',{icon:3, title:'提示信息'},function(index){
				var index = layer.msg('删除中，请稍候',{icon: 16,time:false,shade:0.8});
                var userIds = [];
                for(var j=0;j<$checked.length;j++){
                    var userId = $checked.eq(j).parents("tr").find(".userFrozen").attr("data-id");
                    userIds.push(userId);
                }
                post("/user/batch/status/" + JSON.stringify(userIds), {"status":-1}, function (data) {
                    console.log(data)
                    if(data.code==0){
                        layer.msg(data.msg || "操作成功~", {icon: 6});
                        $('.users_list input[type="checkbox"]').prop("checked",false);
                        dataList(1);
                        form.render();
                    }
                }, false, false);
                layer.close(index);
	        })
		}else{
			layer.msg("请选择需要冻结的用户");
		}
	})

    //全选
	form.on('checkbox(allChoose)', function(data){
		var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
		child.each(function(index, item){
			item.checked = data.elem.checked;
		});
		form.render('checkbox');
	});

	//通过判断文章是否全部选中来确定全选按钮是否选中
	form.on("checkbox(choose)",function(data){
		var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
		var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"]):checked')
		if(childChecked.length == child.length){
			$(data.elem).parents('table').find('thead input#allChoose').get(0).checked = true;
		}else{
			$(data.elem).parents('table').find('thead input#allChoose').get(0).checked = false;
		}
		form.render('checkbox');
	})


    /**
     * 冻结用户
     */
	$("body").on("click",".users_del",function(){
		var _this = $(this);
		layer.confirm('确定冻结该用户？',{icon:3, title:'提示信息'},function(index){
			var id = _this.attr("data-id");
			if(!id){
				return;
			}
            post("/user/update/status/" + id, {"status":3}, function (data) {
                layer.msg(data.msg || "操作成功~", {icon: 6});
                _this.parents("tr").remove();
                layer.close(index);
            }, false, false);

		});
	})


})

function headimg(img) {
    layer.open({
        type: 1,
        title: false,
        closeBtn: 0,
		area:'30%',
        skin: 'layui-layer-nobg', //没有背景色
        shadeClose: true,
        content: '<img src="'+img+'?imageView2/0/w/773/h/520">',
        success: function(layero, index) {
            layer.iframeAuto(index);
        }
    });
}